package com.topisv.tms.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Department;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.User;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.DepartmentService;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * Task管理的Controller, 使用Restful风格的Urls:
 * 
 * List page     : GET /department/
 * Create page   : GET /department/create
 * Create action : POST /department/create
 * Update page   : GET /department/update/{id}
 * Update action : POST /department/update
 * Delete action : GET /department/delete/{id}
 * 
 * @author Arthur
 */
@Controller
@RequestMapping(value = "/department")
public class DepartmentController extends BaseDataTableController{

	/*private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	static {
		sortTypes.put("auto", "自动");
		sortTypes.put("deptname", "部门名");
	}*/

	@Autowired
	private DepartmentService departmentService;
	
	@Autowired
	private AreaGroupService areaGroupService;

	@RequestMapping(value = "v2_show")
	public String list() {
		return "department/departmentList";
	}
	@RequestMapping(value = "page",method = RequestMethod.POST)
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson);
			paramHolder.getSearchParams().put("EQ_status", "1");
			Page<Department> page = departmentService.getDepartment(paramHolder);
			// 封装查询结果
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			
		}
	}
	@RequestMapping(value = "v2_create", method = RequestMethod.GET)
	public String createForm(Model model) {
		List<Map> departments = departmentService.getDepartmentTree();
		model.addAttribute("departments", departments);
		List<AreaGroup> areaGroups = areaGroupService.findAll();
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("department", new Department());
		model.addAttribute("action", "create");
		return "department/departmentForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Department department, RedirectAttributes redirectAttributes) {
		AreaGroup areaGroup = areaGroupService.getAreaGroup(department.getAreagroupId());
		department.setAreaGroup(areaGroup);
		Department department2 = departmentService.getDepartment(department.getParentId());
		department.setDepartment(department2);
		departmentService.saveDepartment(department);
		redirectAttributes.addFlashAttribute("message", "创建部门成功");
		return "redirect:/department/v2_show";
	}

	@RequestMapping(value = "v2_update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model) {
		List<Map>  departments = departmentService.getDepartmentTree();
		model.addAttribute("departments", departments);
		List<AreaGroup> areaGroups = areaGroupService.findAll();
		model.addAttribute("areaGroups", areaGroups);
		model.addAttribute("department", departmentService.getDepartment(id));
		model.addAttribute("action", "update");
		return "department/departmentForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("preloadDepartment") Department department, RedirectAttributes redirectAttributes) {
		AreaGroup areaGroup = areaGroupService.getAreaGroup(department.getAreagroupId());
		department.setAreaGroup(areaGroup);
		Department department2 = departmentService.getDepartment(department.getParentId());
		department.setDepartment(department2);
		departmentService.saveDepartment(department);
		redirectAttributes.addFlashAttribute("message", "更新部门成功");
		return "redirect:/department/v2_show";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		List<User> users= departmentService.findByDepartmentId(id);
		for(User user: users){
			user.setDepartmentId(null);
		}
		List<Department> departments= departmentService.getSubDepartmentById(id);
		for(Department department: departments){
			department.setDepartment(departmentService.getDepartment(1L));
		}
		departmentService.deleteDepartment(id);
		redirectAttributes.addFlashAttribute("message", "删除部门成功");
		return "redirect:/department/v2_show";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadDepartment")
	public Department getDepartment(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return departmentService.getDepartment(id);
		}
		return null;
	}

}